export function tree2List(nodes, arr = [], parentId = '', rank = 0) {
  for (const item of nodes) {
    arr.push({
      id: item.id,
      name: item.name,
      parentId,
      rank,
      resourceUrl: item.id,
    })
    if (item.children && item.children.length) {
      tree2List(item.children, arr, item.id, rank + 1)
    }
  }
  return arr
}

export function list2Tree(data) {
  // 删除 所有 children,以防止多次调用
  data.forEach((item) => {
    delete item.children
  })

  const map = {}
  data.forEach((item) => {
    map[item.id] = item
  })
  const val = []
  data.forEach((item) => {
    const parent = map[item.parentId]
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      val.push(item)
    }
  })
  return val
}

// 查找node
export function treeFind(tree, func) {
  for (const data of tree) {
    if (func(data)) return data
    if (data.children) {
      const res = treeFind(data.children, func)
      if (res) return res
    }
  }
  return null
}
